var bmap = require("../../libs/bmap-wx.min.js");
const util = require('../../util/util.js')
const mapTool = require("../../libs/IsPtInPoly.js");
Page({
  data: {
    latitude: 31.294215390611186,
    longitude: 120.56567126803878,
    buttonText: '开始播放', // 初始按钮文本
    buttonColor: '#07c160', // 初始按钮颜色
    VID: '',
    points: [],
    polyline: [],
    labelStart: {
      latitude: 0,
      longitude: 0,
      content: '',
      color: '#FF0000',
      fontSize: 14,
      bgColor: '#FFFFFF',
      borderRadius: 4,
      padding: 4,
    },
    markerHT: {
      longitude: 0,
      latitude: 0,
      height: 40,
      width: 40,
      rotate: 0,
      zIndex: 2,
      iconPath: "../../image/historyTrajectory/HistoryMarker.png"
    },
    markerStart: {
      content: "起点",
      longitude: 0,
      latitude: 0,
      height: 34,
      width: 42,
      zIndex: 1,
      iconPath: "../../image/historyTrajectory/begin.png",
      label: {
        content: '',
        color: '#000000',
        borderColor: '#333333',
        fontSize: 14,
        bgColor: '#FFFFFF',
        borderRadius: 4,
        padding: 4,
        anchorX: -80,
        anchorY: -68,
      },
    },
    markerEnd: {
      content: "终点",
      longitude: 0,
      latitude: 0,
      height: 34,
      width: 42,
      zIndex: 1,
      iconPath: "../../image/historyTrajectory/end.png",
      label: {
        content: '',
        color: '#000000',
        borderColor: '#333333',
        fontSize: 14,
        bgColor: '#FFFFFF',
        borderRadius: 4,
        padding: 4,
        anchorX: -80,
        anchorY: -68,
      },
    },
    centerMarker: [],
    timeStart: null, //时分秒，根据需要选择
    timeEnd: null, //时分秒，根据需要选择
    stepHistory: 0,
    currentIndex: 0, // 当前播放的轨迹点索引
    timer: null, // 定时器
    scale: 13, // 初始地图缩放级别
    // markers: [{
    //   id: 0,
    //   latitude: 0,
    //   longitude: 0
    // }],
    // 参考：https://developers.weixin.qq.com/miniprogram/dev/component/map.html#%E5%9C%B0%E5%9B%BE%E5%9F%BA%E7%A1%80%E5%B1%9E%E6%80%A7
    // points2: [{
    //   latitude: 31.295164416703983,
    //   longitude: 120.56518388969246
    // }, {
    //   latitude: 31.294412652555245,
    //   longitude: 120.56502295715764
    // }, {
    //   latitude: 31.294192622889625,
    //   longitude: 120.5657096026395
    // }, {
    //   latitude: 31.294385148875147,
    //   longitude: 120.56706143593188
    // }, {
    //   latitude: 31.29492605311089,
    //   longitude: 120.56698633408232
    // }, {
    //   latitude: 31.295411947489562,
    //   longitude: 120.56676102853358
    // }, {
    //   latitude: 31.295402779694275,
    //   longitude: 120.56583834866736
    // }],
  },
  onLoad: function (options) {
    this.setData({
      VID: options.VID
    })
    if (options.hasOwnProperty('SD')) {
      this.setData({
        timeStart: options.SD,
        timeEnd: options.ED,
      })
    } else {
      const currentDate = new Date();
      this.setData({
        timeEnd: util.formatDateTime(currentDate, true)
      })
      currentDate.setDate(currentDate.getDate() - 1);
      this.setData({
        timeStart: util.formatDateTime(currentDate, true)
      })
    }

    var BMap = new bmap.BMapWX({
      ak: "tEmJ2Qdq06YVa1mZDxrz509Cquqom80H",
    });

    this.getHistoryTrajectory();
  },
  onUnload: function () {
    // this.playStop()
  },
  openTypeF () {
    this.setData({
      typeF: true
    })
  },
  selectDateStartChange (e) {
    this.setData({
      timeStart: e.detail.value
    })
    console.log(this.data.timeStart);
  },
  selectDateEndChange (e) {
    this.setData({
      timeEnd: e.detail.value
    })
    console.log(this.data.timeEnd);
  },

  // 播放路径
  playTrack () {
    this.data.timer = setInterval(() => {
      console.log(this.data.currentIndex, '播放')
      if (this.data.currentIndex >= this.data.points.length) {
        clearInterval(this.data.timer);
        return;
      }
      const point = this.data.points[this.data.currentIndex];
      this.setData({
        // latitude: point.latitude,
        // longitude: point.longitude,
        'markerHT.latitude': point.latitude,
        'markerHT.longitude': point.longitude,
        centerMarker: [this.data.markerStart, this.data.markerEnd, this.data.markerHT],
      });
      this.isMarkerInRegion(point);
      this.data.currentIndex++;
    }, 500);
  },
  playStop () {
    // this.changeAddress(31.295212348469367, 120.567418833339, '挹翠华庭');
    // var that = this;
    clearInterval(null)
    const point = this.data.points[0];
    // this.data.markerHT.latitude = 0;
    //   this.data.markerHT.longitude = 0;
    this.setData({
      currentIndex: 0,
      latitude: point.latitude,
      longitude: point.longitude,
      'markerHT.latitude': 0,
      'markerHT.longitude': 0,
      centerMarker: [this.data.markerStart, this.data.markerEnd, this.data.markerHT],
    });
  },
  playStart () {
    // 切换按钮状态
    var that = this;
    if (this.data.buttonText === '开始播放') {
      that.setData({
        buttonText: '暂停播放',
        buttonColor: 'orange',
        // scale: 13, // 放大地图
      });
      // 开始播放
      this.playTrack()
    } else {
      // 停止播放
      clearInterval(this.data.timer);
      that.setData({
        buttonText: '开始播放',
        buttonColor: '#07c160',
        timer: null,
      });
    }
  },
  // playStart1 () {
  //   // this.data.stepHistory = 0;
  //   var that = this;
  //   // that.data.timer= setInterval(
  //   //     function () {
  //   // TODO 你需要无限循环执行的任务
  //   console.log('setInterval 每过500毫秒执行一次任务')
  //   var dataPoint = that.data.points[that.data.stepHistory];
  //   that.setData({
  //     longitude: dataPoint.longitude,
  //     latitude: dataPoint.latitude,
  //     centerMarker: [{
  //       longitude: dataPoint.longitude,
  //       latitude: dataPoint.latitude,
  //       height: 50,
  //       width: 50,
  //       iconPath: "../../image/historyTrajectory/HistoryMarker.png"
  //     }]
  //   });
  //   console.log(that.data.centerMarker)
  //   that.data.stepHistory++;
  //   console.log(that.data.stepHistory)
  //   var bool = that.isMarkerInRegion(dataPoint)
  //   if (bool) {
  //     console.log('范围内')
  //   } else {
  //     console.log('范围外')
  //   }
  //   // }, 500); 
  // },
  // function isMarkerInRegion(marker, region) {
  //   const { northwest, southeast } = region;
  //   return marker.latitude >= northwest.lat &&
  //          marker.latitude <= southeast.lat &&
  //          marker.longitude >= northwest.lng &&
  //          marker.longitude <= southeast.lng;
  // }
  // changeAddress(latitude, longitude, name) {
  //   const result = mapTool.IsPtInPoly(latitude, longitude, this.data.points2)
  //   this.showToast(result, name)
  // },
  // showToast (result, name) {
  //   wx.showToast({
  //     title: result ? name + '在范围内' : name + '不在范围内！',
  //     icon: result ? 'success' : 'error',
  //     duration: 2000
  //   })
  // },
  isMarkerInRegion (marker) {
    var that = this;
    wx.createMapContext('map').getRegion({
      success (res) {
        const { latitude, longitude, latitudeDelta, longitudeDelta } = res;
                // 计算地图显示区域的边界
                const minLat = latitude - latitudeDelta / 2;
                const maxLat = latitude + latitudeDelta / 2;
                const minLng = longitude - longitudeDelta / 2;
                const maxLng = longitude + longitudeDelta / 2;

                // 判断目标经纬度是否在地图范围内
                const isInRange = (
                  marker.latitude >= minLat &&
                  marker.latitude <= maxLat &&
                  marker.longitude >= minLng &&
                  marker.longitude <= maxLng
                );

                if (isInRange) {
                    console.log('目标经纬度在地图范围内');
                } else {
                    console.log('目标经纬度不在地图范围内');
                    that.setData({
                      latitude: marker.latitude,
                      longitude: marker.longitude,
                    })
                }

        // const region = res.region;
        // console.log('region');
        // console.log(region); // { northwest: { lat: ..., lng: ... }, southeast: { lat: ..., lng: ... }, center: { lat: ..., lng: ... }, span: { latitudeDelta: ..., longitudeDelta: ... } }
        // return marker.latitude >= northeast.lat &&
        //   marker.latitude <= southwest.lat &&
        //   marker.longitude >= northwest.lng &&
        //   marker.longitude <= southeast.lng;
      },
      fail (err) {
        console.error(err);
        return false;
      }
    });
    // that.clearInterval(that.data.timer)
  },
  // 获取信息
  getHistoryTrajectory () {
    if (this.data.typeF) {
      this.setData({
        typeF: false
      })
    }
    var that = this;
    wx.request({
      url: "https://www.ejingyou.cn/ServerHuanwei/CompanyapiBDEapi/Vehicle/GetVehicleHistoryInfoXCX",
      data: {
        VID: this.data.VID,
        StartDate: this.data.timeStart,
        EndDate: this.data.timeEnd,
      },
      header: {
        "content-type": "application/json", // 默认值
      },
      success: (res) => {
        console.log(res.data.length)
        if (res.data.length > 0) {
          var linePoint = [];
          for (let index = 0; index < res.data.length; index++) {
            const element = res.data[index];
            if ((index + 1) != res.data.length) {
              const elementNext = res.data[index + 1];
              if (element.LAT === elementNext.LAT && element.LNG === elementNext.LNG) {
              } else {
                linePoint.push({
                  latitude: element.LAT,
                  longitude: element.LNG,
                  GPSTIME: element.GPSTIME
                });
              }
            }
          }

          if (linePoint.length > 0) {

            var polyline = [{
              points: linePoint,
              color: "#ff0000",
              width: 5,
            }];

            that.setData({
              points: linePoint,
              polyline: polyline
            })

            that.setData({
              longitude: linePoint[0].longitude,
              latitude: linePoint[0].latitude,
              'markerStart.latitude': linePoint[0].latitude,
              'markerStart.longitude': linePoint[0].longitude,
              'markerEnd.latitude': linePoint[linePoint.length - 1].latitude,
              'markerEnd.longitude': linePoint[linePoint.length - 1].longitude,
              'markerStart.label.content': linePoint[0].GPSTIME.replace('T', ' '),
              'markerEnd.label.content': linePoint[linePoint.length - 1].GPSTIME.replace('T', ' '),
              centerMarker: [this.data.markerStart, this.data.markerEnd, this.data.markerHT],
              // 'labelStart.latitude': linePoint[0].latitude,
              // 'labelStart.longitude': linePoint[0].longitude,
              // 'labelStart.content': '开始时间',
              // 'labelEnd.latitude': linePoint[linePoint.length - 1].latitude,
              // 'labelEnd.longitude': linePoint[linePoint.length - 1].longitude,
              // 'labelEnd.content': '结束时间',
              // labels: [this.data.labelStart, this.data.labelEnd]
            });

          } else {
            wx.showModal({
              title: '失败',
              content: '您查询时间段，车辆定位未移动，无法形成轨迹',
              showCancel: false
            })
          }
        } else {
          wx.showModal({
            title: '失败',
            content: '未找到轨迹信息',
            showCancel: false
          })
        }
      },
    });
  },
});